<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input v-model="params.name" clearable placeholder="请输入内容" class="search-main" @clear="entersearch" />
      <el-button type="primary" @click="entersearch">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="$router.push('/addEnterprise')">添加企业</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="list" @expand-change="expandChange">
        <el-table-column type="expand">
          <template #default="scope">
            <el-table :data="scope.row.rentList">
              <el-table-column label="租赁楼宇" width="320" prop="buildingName" />
              <el-table-column label="租赁起始时间" prop="startTime">
                <template #default="rentObj">
                  {{ rentObj.row.startTime }}至{{ rentObj.row.endTime }}
                </template>
              </el-table-column>
              <el-table-column label="合同状态" prop="status">
                <template #default="rentObj">
                  <el-tag :type="formatInfoType(rentObj.row.status)">
                    {{ formatStatus(rentObj.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <template #default="scope">
                  <el-button
                    v-permission="'park:rent:add_surrender'"
                    size="mini"
                    type="text"
                    :disabled="scope.row.status===3"
                    @click="rentOut(scope.row.id)"
                  >退租</el-button>
                  <el-button v-permission="'park:rent:remove'" size="mini" type="text" :disabled="scope.row.status!==3">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" :index="indexMethod" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column
          label="联系电话"
          prop="contactNumber"
        />
        <el-table-column label="操作">
          <!-- 作用域插槽里面有id -->
          <template #default="scope">
            <el-button v-permission="'park:rent:add_surrender'" size="mini" type="text" @click="add(scope.row.id)">添加合同</el-button>
            <el-button v-permission="'park:enterprise:query'" size="mini" type="text" @click="$router.push(`/enterpriseDetail/${scope.row.id}`)">查看</el-button>
            <el-button v-permission="'park:enterprise:add_edit'" size="mini" type="text" @click="editpage(scope.row.id)">编辑</el-button>
            <el-button v-permission="'park:enterprise:remove'" size="mini" type="text" @click="deleteEnterprise(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        layout="total, prev, pager, next"
        :total="total"
        :page-size="2"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 添加合同 -->
    <el-dialog
      title="添加合同"
      :visible="rentDialogVisible"
      width="580px"
      @close="closeDialog"
    >
      <span slot="footer" class="dialog-footer">
        <el-button @click="rentDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAdd">确 定</el-button>
      </span>
      <!-- 表单区域 -->
      <div class="form-container">
        <el-form ref="addForm" :model="rentForm" :rules="rentRules" label-position="top">
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select v-model="rentForm.buildingId" placeholder="请选择">
              <el-option
                v-for="item in rentBulidList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="租赁起止日期" prop="rentTime">
            <el-date-picker
              v-model="rentForm.rentTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item label="租赁合同" prop="contractId">
            <el-upload
              ref="upload"
              action="#"
              :http-request="httpRequest"
              :before-upload="beforeUpload"
              :limit="1"
              :on-exceed="onExceed"
              :on-remove="onRemove"
            >
              <el-button size="small" type="primary" plain>上传合同文件</el-button>
              <div slot="tip" class="el-upload__tip">支持扩展名：.doc .docx .pdf, 文件大小不超过5M</div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog></div>
</template>
<script>
import { getEnterpriseListAPI, deleteEnterpriseApi, rentBulidApi, createRentAPI, enterpriseRent, enterpriseRentAPi } from '@/api/Enterprise'
import { getupdatAPI } from '@/api/common'
import { mapState } from 'vuex'
export default {
  name: 'Enterprise',
  data() {
    return {
      // element-ui中的确认取消按钮
      count: true,
      rentForm: {
        buildingId: null, // 楼宇id
        contractId: null, // 合同id
        contractUrl: '', // 合同Url
        enterpriseId: null, // 企业名称
        type: 0, // 合同类型
        rentTime: [] // 合同时间
      },
      rentBulidList: [],
      rentRules: {
        buildingId: [
          { required: true, message: '请选择楼宇', trigger: 'change' }
        ],
        rentTime: [
          { required: true, message: '请选择租赁日期', trigger: 'change' }
        ],
        contractId: [
          { required: true, message: '请上传合同文件', trigger: 'change' }
        ]
      },
      params: {
        // 企业名称
        name: '',
        // 页数
        page: '1',
        // 一页显示的条数
        pageSize: '2'
      },
      list: [],
      total: 0,
      rentDialogVisible: false
    }
  },
  computed: {
    // 是 Vuex 中 mapState 辅助函数的一种用法，它用于将 Vuex store 中指定模块的状态映射到 Vue 组件的计算属性中。这里的 mapState 接受两个参数：
    ...mapState('menu', ['permission'])
  },
  // 计算属性是对象,只有那些生命周期钩子函数才写成函数
  created() {
    console.log(this.permissio)

    this.getEnterpriseList()
  },
  methods: {
    // 退租
    rentOut(id) {
      // console.log(id)
      this.$confirm('你确定退租吗', '温馨提示').then(() => {
        enterpriseRentAPi(id)
        this.$message.success('退租成功')
      }).catch(() => {})
    },
    // 标签和状态
    formatInfoType(status) {
      const MAP = {
        0: 'warning',
        1: 'success',
        2: 'info',
        3: 'danger'
      }
      // return 格式化之后的中文显示
      return MAP[status]
    },
    // 格式化
    formatStatus(status) {
      const TYPEMAP = {
        0: '待生效',
        1: '生效中',
        2: '已到期',
        3: '已退租'
      }
      return TYPEMAP[status]
    },
    // 点击展开的时候会触发的事件
    async expandChange(row, expandRows) {
      // 判断当前的状态是打开还是关闭
      // const isInclude = expandRows.find(item => item.id === row.id)
      // if (!isInclude) return
      // 也可以用下面的这个方法用来判断
      if (this.count) {
        this.count = !this.count
        const res = await enterpriseRent(row.id)
        // eslint-disable-next-line require-atomic-updates
        row.rentList = res.data
        console.log(res)
      } else {
        this.count = !this.count
      }
    },
    onExceed(file) {
      console.log(file)
    },
    // 点击叉号清除
    onRemove(file) {
      console.log(file)
      // 让文件中的id清除
      this.rentForm.contractId = ''
      this.rentForm.contractUrl = ''
      // 校验图片上传文件上传等不属于表单的校验
      this.$refs.addForm.validateField('contractId')
    },
    // 确认按钮
    confirmAdd() {
      this.$refs.addForm.validate(async flag => {
        if (!flag) return
        const [startTime, endTime] = this.rentForm.rentTime
        // 在前面的对象中没有定义,也可以写
        this.rentForm.startTime = startTime
        this.rentForm.endTime = endTime
        console.log(typeof startTime)

        delete this.rentForm.rentTime
        await createRentAPI(this.rentForm)
        this.$message.success('添加合同成功')
        this.getEnterpriseList()
        this.closeDialog()
        // 清空上传文件
        this.$refs.upload.clearFiles()
      })
    },
    // 上传前的校验
    beforeUpload(file) {
      // 要求可以上传的三个文件后缀名称
      const typeList = [
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/msword',
        'application/pdf']
      const fileType = typeList.includes(file.type)
      // 校验尺寸
      const isLt5M = file.size / 1024 / 1024 < 5
      if (fileType && isLt5M) {
        return true
      } else {
        this.$message.warning('上传文件不符合要求，请重新上传')
        return false
      }
    },
    // 这个函数中包含的有前面接口需要的file信息
    async httpRequest({ file }) {
      // 在提交文件和图片的时候必须用的
      const formData = new FormData()
      formData.append('file', file)
      formData.append('type', 2)
      const res = await getupdatAPI(formData)
      this.rentForm.contractId = res.data.id
      this.rentForm.contractUrl = res.data.url
      // 校验图片上传文件上传等不属于表单的校验
      this.$refs.addForm.validateField('contractId')
    },
    // rentBulidApi
    // 获取楼宇框数据
    async add(id) {
      console.log(id)
      this.rentDialogVisible = true
      const res = await rentBulidApi()
      console.log(res)
      this.rentBulidList = res.data
      this.rentForm.enterpriseId = id
    },
    // 关闭模态框
    closeDialog() {
      this.rentDialogVisible = false
      // 清空表单
      this.$refs.addForm.resetFields()
      this.rentForm = {
        buildingId: null, // 楼宇id
        contractId: null, // 合同id
        contractUrl: '', // 合同Url
        enterpriseId: null, // 企业名称
        type: 0, // 合同类型
        rentTime: [] // 合同时间
      }
    },
    // 删除
    deleteEnterprise(id) {
      // console.log(id)
      this.$confirm('您确定删除该企业吗?', '温馨提示').then(
        async() => {
          await deleteEnterpriseApi(id)
          this.$message.success('删除成功')
          this.getEnterpriseList()
        }
      ).catch(() => {})
    },
    // 清空
    // 查询问题
    editpage(id) {
      // console.log(id)
      // 实现跳转和添加id
      this.$router.push({
        path: '/addEnterprise',
        query: {
          id
        }
      })
    },
    entersearch() {
      this.params.page = 1
      // console.log(1)
      this.getEnterpriseList()
    },
    // 处理序号问题
    indexMethod(index) {
      return (this.params.page - 1) * this.params.pageSize + index + 1
    },
    // 分页数据处理
    handleCurrentChange(val) {
      console.log(val)
      this.params.page = val
      this.getEnterpriseList()
    },
    // 数据渲染
    async getEnterpriseList() {
      const res = await getEnterpriseListAPI(this.params)
      // console.log(res)
      this.list = res.data.rows
      this.total = res.data.total
      // 给列表中的每一个添加额外的属性
      this.list = res.data.rows.map(item => {
        return {
          ...item,
          rentList: []
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.department-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container{
  margin: 10px 0px;
}
.page-container{
  padding:4px 0px;
  text-align: right;
}
.form-container{
  padding:0px 80px;
}
</style>
